var mongo= require("mongoose");
var all_models = {};
var events = require('events');

module.exports = function(opts){
	mongo.connect(opts.db_uri,function(err){
		if(err){
			console.dir(err);
		}
	});

	return {
		build:build
	};
}

module.exports.getModel = function(model_name){
	var model_names = model_name.split("_");
	if(!model_names[0] || !model_names[1] 
			|| !all_models[model_names[0]]) return null;
	return all_models[model_names[0]][model_names[1]];
}

function build(app_module){
	var models = {};

	all_models[app_module.app_name]=models;

	function getModel(model_name){
		if(!model_name){		
			return ;
		}

		var M = models[model_name];
		if(!M){
			return ;
		}

		return M;
	}

	var regist = function(model_name,properties){
		//console.dir(model_name);
		if(models[model_name]){
			return models[model_name];
		}

		//console.dir(models);

		var props = {
			id : String,
			ctime : Date,
			utime : Date,
			creator : String
		};

		for(var p in properties){
			props[p] = properties[p];
		}

		var model_schema = new mongo.Schema(props);
		var model_ = models[model_name]
			= mongo.model(model_name,model_schema,app_module.app_name+"_"+model_name);

		models[model_name] = model_;
		
		model_.emitter = new events.EventEmitter();
		model_.on = function(action,callback){
			model_.emitter.on(action,callback);
		}

		model_.emit = function(action,opts1){
			model_.emitter.emit(action,opts1);
		}

		model_.on_action = function(action_name,handler){
			model_.emitter.on("action_"+action_name,handler);
		}

		model_.emit_action = function(action_name,context){
			model_.emitter.emit("action_"+action_name,context);
		}

		return model_;
	}

	return {
		models: models,
		app_name: app_module.app_name,
		getModel: getModel,
		regist: regist
	}
}


